package testdb;

import java.io.PrintWriter;
import java.sql.Connection;

public abstract class DbTest {
    protected Connection connection;
    protected Record record;
    
    protected PrintWriter writer;

    public DbTest(PrintWriter writer, Record record) {
        this.writer = writer;
        this.record = record;
    }

    protected abstract String getName();

    protected abstract void insertTest() throws Exception;

    protected abstract void selectTest() throws Exception;

    protected abstract String connect() throws Exception;
    
    protected abstract void deleteAllData() throws Exception;
    
    protected abstract String getConnectionString();

    private void disconnect() throws Exception {
        connection.close();
        connection = null;
    }
    
    private void safeDisconnect() {
        writer.println("close connection");
        try {
            disconnect();
        } catch (Exception ex) {
            ex.printStackTrace(writer);
        }
    }

    private void executeInsertTest() {
        try {
            writer.format("connect to [%s]\n", getConnectionString());
            connect();
            
            // delete all from table
            writer.println("delete all data from table");
            deleteAllData();

            writer.println("starting INSERT test");
            long timer = -System.currentTimeMillis();
            insertTest();
            timer += System.currentTimeMillis();

            writer.format("time executing for INSERT test: %d ms\n", timer);
        } catch (Exception ex) {
            ex.printStackTrace(writer);
        } finally {
            safeDisconnect();
        }
    }

    private void executeSelectTest() {
        try {
            writer.format("connect to [%s]\n", getConnectionString());
            connect();

            writer.println("starting SELECT test");
            long timer = -System.currentTimeMillis();
            selectTest();
            timer += System.currentTimeMillis();

            writer.format("time executing for SELECT test: %d ms\n", timer);
        } catch (Exception ex) {
            ex.printStackTrace(writer);
        } finally {
            safeDisconnect();
        }
    }

    public void execute() {
        writer.format("Starting %s tests...\n", getName());
        executeInsertTest();
        executeSelectTest();
        writer.format("Complete %s tests\n\n", getName());
    }
}
